#!/bin/sh

BuildTexList()
{
    SearchFolder="$1"
    FolderName="$2"
    ListName="$3"
    OutDir="$4"

    OutFile="$OutDir/$ListName.tex"
    rm -f "$OutFile"
    for F in $SearchFolder/*; do
        TexName=`basename "$F"|cut -f1 -d'.'`
        if test "$TexName" = "*"; then
            continue;
        fi
        echo "$FolderName/$TexName" >> "$OutFile"
    done
}

# Check the arguments
FOLDER="$1"
OUTDIR="$2"

if test ! -d "$FOLDER"; then
    echo "The folder '$FOLDER' doesn't exists."
    exit 1
fi

if test ! -d "$OUTDIR"; then
    echo "The output target '$OUTDIR' doesn't exist."
    exit 1
fi

# Iterate though each subfolder
for D in `find $FOLDER -type d`; do
    # Discard hidden folders
    HIDDEN=`echo "$D" | grep "/\\."`
    if test "$HIDDEN" -o "$D" = "."; then
        continue
    fi
    
    SUBFOLDER=`echo "$D" | sed "s&$FOLDER/&&"`
    LISTNAME=`echo "$SUBFOLDER" | sed "s:/:_:g"`
    BuildTexList "$FOLDER/$SUBFOLDER" "$SUBFOLDER" "$LISTNAME" "$OUTDIR"
done

